package com.library.admin.controller;

import com.framework.Encrypt;
import com.framework.Page;
import com.framework.ReturnJson;
import com.framework.SendMessage;
import com.library.admin.service.AdminServiceImpl;
import com.library.admin.util.AdminState;
import com.library.book.service.BookServiceImpl;
import com.library.book.util.BookState;
import com.library.bookClass.service.BookClassServiceImpl;
import com.library.borrow.service.BorrowServiceImpl;
import com.library.borrow.util.BorrowState;
import com.library.circles.service.CirclesServiceImpl;
import com.library.collection.service.CollectionServiceImpl;
import com.library.count.service.CountServiceImpl;
import com.library.entity.*;
import com.library.entity.Collection;
import com.library.evaluate.service.EvaluateServiceImpl;
import com.library.payment.service.PaymentServiceImpl;
import com.library.power.service.PowerServiceImpl;
import com.library.praise.service.PraiseServiceImpl;
import com.library.recommendation.service.RecommendationServiceImpl;
import com.library.role.service.RoleServiceImpl;
import com.library.search.service.SearchServiceImpl;
import com.library.staff.service.StaffServiceImpl;
import com.library.staff.util.StaffState;
import com.library.statistic.service.StatisticServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("admin")
public class AdminController {
	
	@Resource
	private AdminServiceImpl adminServiceImpl;
	@Resource
	private StaffServiceImpl staffServiceImpl;
    @Resource
    private BookServiceImpl bookServiceImpl;
    @Resource
    private BookClassServiceImpl bookClassServiceImpl;
    @Resource
    private BorrowServiceImpl borrowServiceImpl;
    @Resource
    private PaymentServiceImpl paymentServiceImpl;
    @Resource
    private EvaluateServiceImpl evaluateServiceImpl;
    @Resource
    private PraiseServiceImpl praiseServiceImpl;
    @Resource
    private PowerServiceImpl powerServiceImpl;
    @Resource
    private RoleServiceImpl roleServiceImpl;
    @Resource
    private CountServiceImpl countServiceImpl;
    @Resource
    private SearchServiceImpl searchServiceImpl;
    @Resource
    private StatisticServiceImpl statisticServiceImpl;
    @Resource
    private CollectionServiceImpl collectionServiceImpl;
    @Resource
    private CirclesServiceImpl circlesServiceImpl;
    @Resource
    private RecommendationServiceImpl recommendationServiceImpl;

    /****************管理员**************/
    /*登录*/
	@RequestMapping("login")
	public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam("checkCode") String checkCode,
                        HttpSession session, HttpServletRequest request){
        String trueCode = (String) session.getAttribute("verCode");
        if(!checkCode.equalsIgnoreCase(trueCode)){
            request.setAttribute("error","验证码错误,请重新输入");
            return "login";
        }

		Administrator admin = this.adminServiceImpl.login(username,password);
        Set<Power> powers = new TreeSet<>(new Comparator<Power>() {
            @Override
            public int compare(Power o1, Power o2) {
                if(o1.getType() > o2.getType()){
                    return 1;
                }else if(o1.getType() < o2.getType()){
                    return -1;
                }
                return 0;
            }
        });

        if(admin!=null){

            if(admin.isState()){  //是否被禁用
                request.setAttribute("error","该账户已经被禁用，请联系超级管理员");
                return "login";
            }
            if(admin.getRole() != null)
                powers.addAll(admin.getRole().getPowers());


            //清除之前的会话信息
            Enumeration em  = session.getAttributeNames();
            while(em.hasMoreElements()){
                session.removeAttribute(em.nextElement().toString());
            }

            List<BookClass> bookClasses = this.bookClassServiceImpl.getAllBookClasses();    //全部图书类别 用于统计
            this.statisticServiceImpl.updateAllBookClassStatistic(bookClasses); //更新图书类别总统计

            session.setAttribute("powers",powers);
            session.setAttribute("role",admin.getRole());
            session.setAttribute("admin",admin);

            if(admin.getRank()){
                return "redirect:/admin/addAdminPage";
            }else{
                return "redirect:/admin/addStaffPage";
            }
		} else{
            request.setAttribute("error","账号密码不一致");
			return "login";
		}
	}
	/* 退出登录*/
    @RequestMapping("loginOut")
    public String loginOut(HttpSession session){
        session.invalidate();
        return "login";
    }

    /*设置自己的信息*/
    @RequestMapping("adminInfoUpdatePage")
    public String staffInfoUpdatePage(HttpSession session,HttpServletRequest request,RedirectAttributes attr){
        Administrator admin = (Administrator) session.getAttribute("admin");

        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        request.setAttribute("admin",admin);
        session.setAttribute("admin",admin);
        return "admin/admin_my_info";
    }

    /* 跳转到修改密码*/
    @RequestMapping("updatePasswordPage")
    public String updatePasswordPage(RedirectAttributes attr,HttpServletRequest request){
        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        return "admin/admin_password";
    }

    /* 找回密码 生成验证码操作*/
    @ResponseBody
    @RequestMapping(value = "findPasswordEmailCode",method = RequestMethod.POST)
    public ReturnJson findPasswordEmailCode(@RequestBody Map<String, String> params,HttpSession session){
        String username = params.get("username");
        String subject = "内部图书管理系统_信息找回";
        Map<String,Object> data = new HashMap();

        /*判断员工是否存在*/
        if(this.adminServiceImpl.getAdmin(username) == null){
            return new ReturnJson(false,"失败了，用户不存在");
        }else{
            Administrator admin = this.adminServiceImpl.getAdmin(username);
            String emailCode= String.valueOf((int)(Math.random()*1000000));

            session.setAttribute("emailCode",emailCode);        //邮件随机码
            session.setAttribute("userCode",username);      //用户名码
            new SendMessage().send("companylibrary@sina.com","administrator",admin.getEmail(),subject,emailCode);      /* 发送邮件 */
            return new ReturnJson(true,null,data);
        }
    }

    /* 找回密码*/
    @RequestMapping("findPassword")
    public String findPassword(@RequestParam("username") String username,
                                @RequestParam("emailCode") String emailCode,
                                HttpServletRequest request,HttpSession session){
        String trueCode = (String) session.getAttribute("emailCode");
        Administrator admin = this.adminServiceImpl.getAdmin(username);

        if(!emailCode.equals(trueCode)) {
            request.setAttribute("error", "验证码错误,请重新输入");
            return "findPassword";
        } else if(admin == null || !username.equals(session.getAttribute("userCode"))){
            request.setAttribute("error", "用户名不存在或者不一致,请重新输入");
            return "findPassword";
        } else {
            /* 发送邮件 */
            String newPassword = trueCode;

            admin.setPassword(newPassword);
            this.adminServiceImpl.updateAdminPassword(admin);
            request.setAttribute("success","密码已设置为验证码,请及时登录并修改密码");
            session.invalidate();
        }
        return "login";
    }

    /* 跳转到修改个人信息页面*/
    @RequestMapping("updateInfoPage")
    public String updateInfoPage(RedirectAttributes attr,HttpServletRequest request){
        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        return "admin/admin_my_info";
    }

    /* 修改个人信息操作*/
    @RequestMapping(value = "updateInfo",method = RequestMethod.POST)
    public String updateInfo(@RequestParam("email") String email,
                                 HttpSession session,HttpServletRequest request,RedirectAttributes attr){
        Administrator admin = (Administrator) session.getAttribute("admin");

        admin.setEmail(email);  // 电子邮箱
        this.adminServiceImpl.updateAdmin(admin);

        attr.addFlashAttribute("success","修改成功");
        session.setAttribute("admin",admin);
        return "redirect:/admin/updateInfoPage";
    }

    /* 修改密码操作*/
    @RequestMapping(value = "updatePassword",method = RequestMethod.POST)
    public String updatePassword(@RequestParam("old_password") String oldPassword,
                                 @RequestParam("new_password") String newPassword,
                                 HttpSession session,HttpServletRequest request,RedirectAttributes attr){
        Administrator admin = (Administrator) session.getAttribute("admin");

        if(!Encrypt.SHA512(oldPassword).equals(admin.getPassword())){
            attr.addFlashAttribute("error","原密码不正确");
            return "redirect:/admin/updatePasswordPage";
        }
        admin.setPassword(newPassword);
        this.adminServiceImpl.updateAdminPassword(admin);

        attr.addFlashAttribute("success","修改成功");
        session.setAttribute("admin",admin);
        return "redirect:/admin/updatePasswordPage";
    }

    /******************管理员管理：基本增删改查***************/
     /* 跳转到添加管理员*/
    @RequestMapping("addAdminPage")
    public String addAdminPage(HttpServletRequest request,RedirectAttributes attr){
        List<Role> roles = this.roleServiceImpl.getAllRoles();

        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        request.setAttribute("roles",roles);
        return "admin/admin_admin_manage/admin_admin_add";
    }

    /* 添加管理员操作*/
    @RequestMapping(value = "addAdmin",method = RequestMethod.POST)
    public String addAdmin(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("roleId") String roleId,
                           @RequestParam("adminName") String name,
                           HttpServletRequest request,RedirectAttributes attr){
        /*判断用户名是否存在*/
        if(this.adminServiceImpl.getAdmin(username) != null){
            attr.addFlashAttribute("success","用户名已经存在");
            return "redirect:/admin/addAdminPage";
        }
        Administrator administrator = new Administrator();
        administrator.setUsername(username);
        administrator.setPassword(password);
        administrator.setName(name);
        administrator.setRank(false);
        administrator.setState(AdminState.ENABLE.getState());

        if(!roleId.equals("")){
            Role role = this.roleServiceImpl.getRole(Integer.parseInt(roleId));
            administrator.setRole(role);
        }
        this.adminServiceImpl.addAdmin(administrator);

        attr.addFlashAttribute("success","添加成功");
        return "redirect:/admin/addAdminPage";
    }

    /* 更新管理员信息页面*/
    @RequestMapping("editAdminPage")
    public String editAdminPage(@RequestParam("adminId") int adminId,
                               HttpServletRequest request){
        Administrator admin = this.adminServiceImpl.getAdmin(adminId);
        List<Role> roles = this.roleServiceImpl.getAllRoles();

        request.setAttribute("roles",roles);
        request.setAttribute("admin",admin);

        return "admin/admin_admin_manage/admin_admin_info";
    }

    /* 更新管理员操作*/
    @RequestMapping(value = "updateAdmin",method = RequestMethod.POST)
    public String updateAdmin(@RequestParam("adminId") int adminId,
                             @RequestParam("adminName") String name,
                             @RequestParam("roleId") String roleId,
                             HttpServletRequest request,RedirectAttributes attr){
        Administrator admin = this.adminServiceImpl.getAdmin(adminId);
        if(!roleId.equals("")){
            Role role = this.roleServiceImpl.getRole(Integer.parseInt(roleId));
            admin.setRole(role);
        }else{
            admin.setRole(null);
        }
        admin.setName(name);

        this.adminServiceImpl.updateAdmin(admin);

        attr.addFlashAttribute("success","更新成功!");
        return "redirect:/admin/adminListPage";
    }


    /* 删除管理员操作*/
    @RequestMapping(value = "deleteAdmin",method = RequestMethod.POST)
    public String deleteAdmin(@RequestParam("adminId") String adminId,
                              HttpServletRequest request,RedirectAttributes attr){
        	/*判断用户名是否存在*/
        if(this.adminServiceImpl.getAdmin(Integer.parseInt(adminId)) == null){
            request.setAttribute("error","员工不存在");
            return "redirect:/admin/adminListPage";
        }
        this.adminServiceImpl.deleteAdmin(Integer.parseInt(adminId));
        attr.addFlashAttribute("success","删除成功!");

        return "redirect:/admin/adminListPage";
    }

    /* 删除管理员组操作*/
    @RequestMapping(value = "deleteAdminGroup",method = RequestMethod.POST)
    public String deleteAdminGroup(@RequestParam("adminList") String adminList,
                                   HttpServletRequest request,RedirectAttributes attr){
        String[] admins = adminList.split(",");
        int[] s = new int[admins.length];

        for(int i = 0;i < admins.length;++i){
            s[i] = Integer.parseInt(admins[i]);
        }
        this.adminServiceImpl.deleteAdminGroup(s);
        attr.addFlashAttribute("success","删除成功!");

        return "redirect:/admin/adminListPage";
    }

    /* 禁止管理员操作*/
    @ResponseBody
    @RequestMapping(value = "forbiddenAdmin",method = RequestMethod.POST)
    public ReturnJson forbiddenAdmin(@RequestBody Map<String, String> params){
        String adminId = params.get("adminId");
        Map<String,Object> data = new HashMap();

        	/*判断员工是否存在*/
        if(this.adminServiceImpl.getAdmin(Integer.parseInt(adminId)) == null){
            return new ReturnJson(false,"失败了，管理员不存在");
        }

        Administrator admin = this.adminServiceImpl.getAdmin(Integer.parseInt(adminId));
        admin.setState(AdminState.FORBIDDEN.getState());

        this.adminServiceImpl.updateAdmin(admin);

        data.put("state",AdminState.FORBIDDEN.getState());
        return new ReturnJson(true,null,data);
    }

    /* 解禁管理员操作*/
    @ResponseBody
    @RequestMapping(value = "releaseAdmin",method = RequestMethod.POST)
    public ReturnJson releaseAdmin(@RequestBody Map<String, String> params){
        String adminId = params.get("adminId");
        Map<String,Object> data = new HashMap();

        	/*判断员工是否存在*/
        if(this.adminServiceImpl.getAdmin(Integer.parseInt(adminId)) == null){
            return new ReturnJson(false,"失败了，管理员不存在");
        }

        Administrator admin = this.adminServiceImpl.getAdmin(Integer.parseInt(adminId));
        admin.setState(AdminState.ENABLE.getState());

        this.adminServiceImpl.updateAdmin(admin);

        data.put("state",AdminState.ENABLE.getState());
        return new ReturnJson(true,null,data);
    }

    /* 跳转到管理员列表*/
    @RequestMapping("adminListPage")
    public String adminListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                HttpServletRequest request,RedirectAttributes attr){
        Map<String,Object> paramsMap = new HashMap<>();
        Page<Administrator> adminPage;

        if(pageSize.equals("all")){
            List<Administrator> admins = this.adminServiceImpl.getAllAdmin();
            adminPage = new Page<>();
            adminPage.setPageSize(admins.size());
            adminPage.setTotalCount(admins.size());
            adminPage.setList(admins);
            adminPage.setCurrentPageNum(1);
            adminPage.setTotalPageNum(1);
        }else{
            adminPage = this.adminServiceImpl.getPageByParam(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        Administrator admin;
        for(int i = adminPage.getList().size() - 1;i >= 0;--i){
            admin = adminPage.getList().get(i);
            if(admin.getRank() == true){
                adminPage.getList().remove(admin);
            }
        }

        request.setAttribute("admins",adminPage.getList());
        request.setAttribute("page", adminPage);

        if(attr.getFlashAttributes().get("success") != null){
            request.setAttribute("success",attr.getFlashAttributes().get("success"));
        }else if(attr.getFlashAttributes().get("error") != null){
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        }

        return "admin/admin_admin_manage/admin_admin_list";
    }

    /* 跳转到黑名单列表*/
    @RequestMapping("blackAdminListPage")
    public String blackAdminListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                     @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                     HttpServletRequest request,RedirectAttributes attr){
        Map<String,Object> paramsMap = new HashMap<>();
        Page<Administrator> adminPage;

        if(pageSize.equals("all")){
            List<Administrator> admins = this.adminServiceImpl.getAllBlackAdmins();
            adminPage = new Page<>();
            adminPage.setPageSize(admins.size());
            adminPage.setTotalCount(admins.size());
            adminPage.setList(admins);
            adminPage.setCurrentPageNum(1);
            adminPage.setTotalPageNum(1);
        }else{
            paramsMap.put("state",true);
            adminPage = this.adminServiceImpl.getPageByParam(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        request.setAttribute("admins",adminPage.getList());
        request.setAttribute("page", adminPage);
        request.setAttribute("blackList",true);

        if(attr.getFlashAttributes().get("success") != null){
            request.setAttribute("success",attr.getFlashAttributes().get("success"));
        }else if(attr.getFlashAttributes().get("error") != null){
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        }

        return "admin/admin_admin_manage/admin_admin_list";
    }

/*****************角色管理******************/
    /* 跳转到添加角色列表*/
    @RequestMapping("addRolePage")
    public String addRolePage(HttpServletRequest request,RedirectAttributes attr){
        List<Power> powers = this.powerServiceImpl.getAllPowers();
        request.setAttribute("powers",powers);

        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        return "admin/admin_role_manage/admin_role_add";
    }

    /* 添加角色操作*/
    @RequestMapping(value = "addRole",method = RequestMethod.POST)
    public String addRole(@RequestParam("roleName") String roleName,
                           @RequestParam("powers") String powers,
                           HttpServletRequest request,RedirectAttributes attr){
        Set<Power> powerSet = new HashSet<>();
        if(powers.equals("")){
            Role role = new Role();
            role.setName(roleName);
            role.setPowers(powerSet);
            this.roleServiceImpl.addRole(role);

            attr.addFlashAttribute("success","添加成功");
            return "redirect:/admin/addRolePage";
        }
        String[] powerArr = powers.split(",");
        Role role = new Role();
        Power p;

        role.setName(roleName);
        for(int i = 0;i < powerArr.length;++i){
            p = this.powerServiceImpl.getPower(Integer.parseInt(powerArr[i]));
            powerSet.add(p);
        }
        role.setPowers(powerSet);
        this.roleServiceImpl.addRole(role);

        attr.addFlashAttribute("success","添加成功");

        return "redirect:/admin/addRolePage";
    }

    /* 更新角色信息页面*/
    @RequestMapping("editRolePage")
    public String editRolePage(@RequestParam("roleId") String roleId,
                                HttpServletRequest request){
        Role role = this.roleServiceImpl.getRole(Integer.parseInt(roleId));
        List<Power> powers = this.powerServiceImpl.getAllPowers();

        request.setAttribute("role",role);
        request.setAttribute("powers",powers);

        return "admin/admin_role_manage/admin_role_info";
    }

    /* 更新角色操作*/
    @RequestMapping(value = "updateRole",method = RequestMethod.POST)
    public String updateRole(@RequestParam("roleId") int roleId,
                              @RequestParam("roleName") String roleName,
                              @RequestParam("powers") String powers,
                             HttpServletRequest request,RedirectAttributes attr){
        Set<Power> powerSet = new HashSet<>();
        if(powers.equals("")){
            Role role = this.roleServiceImpl.getRole(roleId);
            role.setName(roleName);
            role.setPowers(powerSet);

            this.roleServiceImpl.editRole(role);
            attr.addFlashAttribute("success","更新成功!");
            return "redirect:/admin/roleListPage";
        }

        String[] powerArr = powers.split(",");
        Power p;
        Role role = this.roleServiceImpl.getRole(roleId);

        role.setName(roleName);
        for(int i = 0;i < powerArr.length;++i){
            p = this.powerServiceImpl.getPower(Integer.parseInt(powerArr[i]));
            powerSet.add(p);
        }
        role.setPowers(powerSet);

        this.roleServiceImpl.editRole(role);

        attr.addFlashAttribute("success","更新成功!");
        return "redirect:/admin/roleListPage";
    }

    /* 删除角色操作*/
    @RequestMapping(value = "deleteRole",method = RequestMethod.POST)
    public String deleteRole(@RequestParam("roleId") String roleId,
                              HttpServletRequest request,RedirectAttributes attr){
		/*判断角色是否存在*/
        if(this.roleServiceImpl.getRole(Integer.parseInt(roleId)) == null){
            attr.addFlashAttribute("error","角色不存在");
            return "redirect:/admin/roleListPage";
        }

        this.roleServiceImpl.deleteRole(Integer.parseInt(roleId));
        attr.addFlashAttribute("success","删除成功");

        return "redirect:/admin/roleListPage";
    }

    /* 删除角色组操作*/
    @RequestMapping(value = "deleteRoleGroup",method = RequestMethod.POST)
    public String deleteRoleGroup(@RequestParam("roleList") String roleList,
                                   HttpServletRequest request,RedirectAttributes attr){
        String[] roles = roleList.split(",");
        int[] r = new int[roles.length];

        for(int i = 0;i < roles.length;++i){
            r[i] = Integer.parseInt(roles[i]);
        }
        this.roleServiceImpl.deleteRoleGroup(r);
        attr.addFlashAttribute("success","删除成功");

        return "redirect:/admin/roleListPage";
    }

    /* 跳转到角色列表*/
    @RequestMapping("roleListPage")
    public String roleListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                               @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                               HttpServletRequest request,RedirectAttributes attr){
        Map<String,Object> paramsMap = new HashMap<>();
        Page<Role> rolePage;

        if(pageSize.equals("all")){
            List<Role> roles = this.roleServiceImpl.getAllRoles();
            rolePage= new Page<>();
            rolePage.setPageSize(roles.size());
            rolePage.setTotalCount(roles.size());
            rolePage.setList(roles);
            rolePage.setCurrentPageNum(1);
            rolePage.setTotalPageNum(1);
        }else{
            rolePage = this.roleServiceImpl.getAllRoles(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        request.setAttribute("roles",rolePage.getList());
        request.setAttribute("page", rolePage);

        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        return "admin/admin_role_manage/admin_role_list";
    }

    /******************员工管理：基本增删改查***************/
    /* 跳转到添加员工*/
	@RequestMapping("addStaffPage")
	public String addStaffPage(HttpServletRequest request,RedirectAttributes attr){
        if(attr.getFlashAttributes().get("success") != null){
            request.setAttribute("success",attr.getFlashAttributes().get("success"));
        }else if(attr.getFlashAttributes().get("error") != null){
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        }
        List<Role> roles = this.roleServiceImpl.getAllRoles();
        request.setAttribute("roles",roles);

        return "admin/admin_staff_manage/admin_staff_add";
	}

	/* 添加员工操作*/
	@RequestMapping(value = "addStaff",method = RequestMethod.POST)
	public String addStaff(@RequestParam("username") String username,
							   @RequestParam("password") String password,
							   @RequestParam("staffName") String staffName,
							   @RequestParam("department") String department,
							   @RequestParam("maxNumber") int number,
                               @RequestParam("roleId") String roleId,
							   HttpServletRequest request,RedirectAttributes attr){
		/*判断用户名是否存在*/
		if(this.staffServiceImpl.getStaff(username) != null){
            attr.addFlashAttribute("error","用户名已经存在");
            return "redirect:/admin/addStaffPage";
		}

		Staff staff = new Staff();

		staff.setUsername(username);        //用户名
		staff.setPassword(password);        //密码
		staff.setName(staffName);           //姓名
        staff.setGrade(1);                  //等级1
		staff.setDepartment(department);    //部门名称
        staff.setState(StaffState.ENABLE.getState());              //状态
		staff.setMaxBorrowNumber(number);   //最大可借数量
        staff.setBorrowedNumber(0);     //已借阅数量

        if(roleId.equals("")){
            staff.setRole(null);
        }else {
            Role role = this.roleServiceImpl.getRole(Integer.parseInt(roleId));
            staff.setRole(role);
        }
		this.staffServiceImpl.addStaff(staff);

        //创建收藏夹
        Collection collection = new Collection();
        collection.setStaff(staff);
        this.collectionServiceImpl.addCollection(collection);
        staff.setCollection(collection);

        //创建朋友圈
        Circles circles = new Circles();
        circles.setStaff(staff);
        this.circlesServiceImpl.addCircles(circles);
        staff.setCircles(circles);

        //创建推荐
        Recommendation recommendation = new Recommendation();
        recommendation.setStaff(staff);
        this.recommendationServiceImpl.addRecommendation(recommendation);
        staff.setRecommendation(recommendation);

        this.staffServiceImpl.updateStaff(staff);

        attr.addFlashAttribute("success","添加成功");

        return "redirect:/admin/addStaffPage";
	}

    /* 删除员工操作*/
    @RequestMapping(value = "deleteStaff",method = RequestMethod.POST)
    public String deleteStaff(@RequestParam("staffId") String staffId,
                               HttpServletRequest request,RedirectAttributes attr){
		/*判断用户是否存在*/
        if(this.staffServiceImpl.getStaff(Integer.parseInt(staffId)) == null){
            attr.addFlashAttribute("error","员工不存在");
            return "redirect:/admin/staffListPage";
        }

		this.staffServiceImpl.deleteStaff(Integer.parseInt(staffId));
        attr.addFlashAttribute("success","删除成功");

        return "redirect:/admin/staffListPage";
    }

    /* 删除员工组操作*/
    @RequestMapping(value = "deleteStaffGroup",method = RequestMethod.POST)
    public String deleteStaffGroup(@RequestParam("staffList") String staffList,
                              HttpServletRequest request,RedirectAttributes attr){
        String[] staffs = staffList.split(",");
        int[] s = new int[staffs.length];

        for(int i = 0;i < staffs.length;++i){
            s[i] = Integer.parseInt(staffs[i]);
        }
        this.staffServiceImpl.deleteStaffGroup(s);
        attr.addFlashAttribute("success","删除成功");

        return "redirect:/admin/staffListPage";
    }

    /* 禁止员工操作*/
    @ResponseBody
    @RequestMapping(value = "forbiddenStaff",method = RequestMethod.POST)
    public ReturnJson forbiddenStaff(@RequestBody Map<String, String> params){
        String staffId = params.get("staffId");
        Map<String,Object> data = new HashMap();

		/*判断员工是否存在*/
        if(this.staffServiceImpl.getStaff(Integer.parseInt(staffId)) == null){
            return new ReturnJson(false,"失败了，员工不存在");
        }
        Staff staff = this.staffServiceImpl.getStaff(Integer.parseInt(staffId));
        staff.setState(StaffState.FORBIDDEN.getState());
        this.staffServiceImpl.updateStaff(staff);
        data.put("state",StaffState.FORBIDDEN.getState());

        return new ReturnJson(true,null,data);
    }

    /* 解禁员工操作*/
    @ResponseBody
    @RequestMapping(value = "releaseStaff",method = RequestMethod.POST)
    public ReturnJson releaseStaff(@RequestBody Map<String, String> params){
        String staffId = params.get("staffId");
        Map<String,Object> data = new HashMap();

		/*判断员工是否存在*/
        if(this.staffServiceImpl.getStaff(Integer.parseInt(staffId)) == null){
            return new ReturnJson(false,"失败了，员工不存在");
        }
        Staff staff = this.staffServiceImpl.getStaff(Integer.parseInt(staffId));
        staff.setState(StaffState.ENABLE.getState());
        this.staffServiceImpl.updateStaff(staff);
        data.put("state",StaffState.ENABLE.getState());

        return new ReturnJson(true,null,data);
    }


	/* 跳转到员工列表*/
	@RequestMapping("staffListPage")
	public String staffListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                 @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                 HttpServletRequest request,RedirectAttributes attr){
        Map<String,Object> paramsMap = new HashMap<>();
        Page<Staff> staffPage;

        if(pageSize.equals("all")){
            List<Staff> staffs = this.staffServiceImpl.getAllStaffs();
            staffPage= new Page<>();
            staffPage.setPageSize(staffs.size());
            staffPage.setTotalCount(staffs.size());
            staffPage.setList(staffs);
            staffPage.setCurrentPageNum(1);
            staffPage.setTotalPageNum(1);
        }else{
            staffPage = this.staffServiceImpl.getPageByParams(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        if(attr.getFlashAttributes().get("success") != null){
            request.setAttribute("success",attr.getFlashAttributes().get("success"));
        }else if(attr.getFlashAttributes().get("error") != null){
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        }

        request.setAttribute("staffs",staffPage.getList());
        request.setAttribute("page", staffPage);

		return "admin/admin_staff_manage/admin_staff_list";
	}

    /* 跳转到黑名单列表*/
    @RequestMapping("blackStaffListPage")
    public String blackStaffListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                      @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                      HttpServletRequest request){
        Map<String,Object> paramsMap = new HashMap<>();
        Page<Staff> staffPage;

        paramsMap.put("state",true);
        if(pageSize.equals("all")){
            List<Staff> staffs = this.staffServiceImpl.getStaffsByParams(paramsMap);
            staffPage= new Page<>();
            staffPage.setPageSize(staffs.size());
            staffPage.setTotalCount(staffs.size());
            staffPage.setList(staffs);
            staffPage.setCurrentPageNum(1);
            staffPage.setTotalPageNum(1);
        }else{
            staffPage = this.staffServiceImpl.getPageByParams(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        request.setAttribute("staffs",staffPage.getList());
        request.setAttribute("page", staffPage);
        request.setAttribute("blackList","1");

        return "admin/admin_staff_manage/admin_staff_list";
    }

	/* 更新员工信息页面*/
	@RequestMapping("editStaffPage")
	public String editStaffPage(@RequestParam("staffId") String staffId,
								 HttpServletRequest request){
		Staff staff = this.staffServiceImpl.getStaff(Integer.parseInt(staffId));
        List<Role> roles = this.roleServiceImpl.getAllRoles();

        request.setAttribute("roles",roles);
		request.setAttribute("staff",staff);

		return "admin/admin_staff_manage/admin_staff_info";
	}

	/* 更新员工信息操作*/
	@RequestMapping(value = "updateStaff",method = RequestMethod.POST)
	public String updateStaff(@RequestParam("staffId") String staffId,
							    @RequestParam("staffName") String staffName,
							    @RequestParam("department") String department,
							    @RequestParam("state") String state,
                                @RequestParam("qq") String qq,
                                @RequestParam("email") String email,
                                @RequestParam("roleId") String roleId,
							    @RequestParam("maxNumber") int maxBorrowNumber,HttpServletRequest request
                                ,RedirectAttributes attr){
		Staff staff = this.staffServiceImpl.getStaff(Integer.parseInt(staffId));
		staff.setState(Boolean.parseBoolean(state));
		staff.setName(staffName);
        staff.setEmail(email);
        staff.setQq(qq);
		staff.setDepartment(department);
		staff.setMaxBorrowNumber(maxBorrowNumber);

        if(roleId.equals("")){
            staff.setRole(null);
        }else {
            Role role = this.roleServiceImpl.getRole(Integer.parseInt(roleId));
            staff.setRole(role);
        }

		this.staffServiceImpl.updateStaff(staff);
        attr.addFlashAttribute("success","更新成功!");

        return "redirect:/admin/staffListPage";
	}

    /******************图书管理：基本增删改查***************/
        /* 跳转到添加图书类别页面*/
    @RequestMapping("addBookClassPage")
    public String addBookClassPage(HttpServletRequest request,RedirectAttributes attr){
        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        return "admin/admin_bookClass_manage/admin_bookClass_add";
    }

    /* 添加图书类别操作*/
    @RequestMapping(value = "addBookClass",method = RequestMethod.POST)
    public String addBookClass(@RequestParam("bookClassName") String bookClassName,
                          RedirectAttributes attr, HttpServletRequest request) throws IOException {
        BookClass bookClass = new BookClass();

        bookClass.setName(bookClassName);
        this.bookClassServiceImpl.addBookClass(bookClass);

        attr.addFlashAttribute("success","添加成功");
        return "redirect:/admin/addBookClassPage";
    }

    /* 跳转到全部图书类别列表*/
    @RequestMapping(value = "bookClassListPage")
    public String bookClassListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                    @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                    HttpServletRequest request,RedirectAttributes attr){
        Map<String,Object> paramsMap = new HashMap<>();
        Page<BookClass> bookClassPage;

        if(pageSize.equals("all")){
            List <BookClass> bookClasses = this.bookClassServiceImpl.getAllBookClasses();
            bookClassPage = new Page<>();
            bookClassPage.setPageSize(bookClasses.size());
            bookClassPage.setTotalCount(bookClasses.size());
            bookClassPage.setList(bookClasses);
            bookClassPage.setCurrentPageNum(1);
            bookClassPage.setTotalPageNum(1);
        }else{
            bookClassPage = this.bookClassServiceImpl.getBookClassPage(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        request.setAttribute("bookClasses",bookClassPage.getList());
        request.setAttribute("page",bookClassPage);

        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        return "admin/admin_bookClass_manage/admin_bookClass_list";
    }

    /* 删除图书操作*/
    @RequestMapping(value = "deleteBookClass",method = RequestMethod.POST)
    public String deleteBookClass(@RequestParam("bookClassId") String bookClassId,
                             HttpServletRequest request,RedirectAttributes attr){
        BookClass bc = this.bookClassServiceImpl.getBookClass(Integer.parseInt(bookClassId));
		/*判断图书是否存在*/
        if(bc == null){
            attr.addFlashAttribute("error","图书类别不存在");
            return "redirect:/admin/bookClassListPage";
        }
        this.bookClassServiceImpl.deleteBookClass(Integer.parseInt(bookClassId));
        attr.addFlashAttribute("success","删除成功");

        return "redirect:/admin/bookClassListPage";
    }

    /* 删除图书类别组操作*/
    @RequestMapping(value = "deleteBookClassGroup",method = RequestMethod.POST)
    public String deleteBookClassGroup(@RequestParam("bookClassList") String bookClassList,
                                  HttpServletRequest request,RedirectAttributes attr){
        String[] bookClasses = bookClassList.split(",");
        int[] bc = new int[bookClasses.length];

        for(int i = 0;i < bookClasses.length;++i){
            bc[i] = Integer.parseInt(bookClasses[i]);
        }
        this.bookClassServiceImpl.deleteBookClassGroup(bc);
        attr.addFlashAttribute("success","删除成功!");

        return "redirect:/admin/bookClassListPage";
    }

    /* 编辑图书类别信息页面*/
    @RequestMapping(value = "editBookClassPage",method = RequestMethod.GET)
    public String editBookClassPage(@RequestParam("bookClassId") String bookClassId,
                                    HttpServletRequest request,RedirectAttributes attr){
        BookClass bookClass = this.bookClassServiceImpl.getBookClass(Integer.parseInt(bookClassId));

        request.setAttribute("bookClass",bookClass);
        request.setAttribute("success",attr.getFlashAttributes().get("success"));

        return "admin/admin_bookClass_manage/admin_bookClass_info";
    }

    /* 更新图书信息操作*/
    @RequestMapping(value = "updateBookClass",method = RequestMethod.POST)
    public String updateStaff(@RequestParam("bookClassId") String bookClassId,
                              @RequestParam("bookClassName") String bookClassName,
                              HttpServletRequest request,RedirectAttributes attr){
        BookClass bookClass = this.bookClassServiceImpl.getBookClass(Integer.parseInt(bookClassId));

        bookClass.setName(bookClassName);
        this.bookClassServiceImpl.editBookClass(bookClass);
        attr.addFlashAttribute("success","更新成功");

        return "redirect:/admin/bookClassListPage";
    }


    /***************图书管理*******************/
    /* 跳转到添加图书页面*/
    @RequestMapping("addBookPage")
    public String addBookPage(HttpServletRequest request,RedirectAttributes attr){
        List<BookClass> bookClasses = this.bookClassServiceImpl.getAllBookClasses();

        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        else if(attr.getFlashAttributes().get("success") != null)
            request.setAttribute("success",attr.getFlashAttributes().get("success"));

        request.setAttribute("bookClasses",bookClasses);
        return "admin/admin_book_manage/admin_book_add";
    }

    /* 添加图书操作*/
    @RequestMapping(value = "addBook",method = RequestMethod.POST)
    public String addBook(@RequestParam("bookName") String bookName,
                               @RequestParam("author") String author,
                               @RequestParam("publish") String publish,
                               @RequestParam("bookClass") String bookClass,
                               @RequestParam("ISBN") String ISBN,
                               @RequestParam("bookPrice") String bookPrice,
                                MultipartHttpServletRequest multipartRequest,
                              RedirectAttributes attr, HttpServletRequest request) throws IOException {
        String contextPath = request.getSession().getServletContext().getRealPath("/");
        MultipartFile imgFile =  multipartRequest.getFile("book_img");
        Book book = new Book();

        book.setName(bookName);
        book.setAuthor(author);
        book.setPublish(publish);
        book.setISBN(ISBN);
        book.setBrowseTimes(0);
        book.setBorrowTimes(0);
        book.setPrice(Float.parseFloat(bookPrice));
        book.setState(BookState.ENABLE_BORROW.getState());
        book.setBookClass(bookClassServiceImpl.getBookClass(Integer.parseInt(bookClass)));

        this.bookServiceImpl.addBook(book,contextPath,imgFile);

        attr.addFlashAttribute("success","添加成功");
        return "redirect:/admin/addBookPage";
    }

    /* 跳转到全部图书列表*/
    @RequestMapping(value = "bookListPage")
    public String bookListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                               @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                               HttpServletRequest request){
        Map<String,Object> paramsMap = new HashMap<>();
        Page<Book> bookPage;

        if(pageSize.equals("all")){
            List <Book> books = this.bookServiceImpl.getAllBooks();
            bookPage = new Page<>();
            bookPage.setPageSize(books.size());
            bookPage.setTotalCount(books.size());
            bookPage.setList(books);
            bookPage.setCurrentPageNum(1);
            bookPage.setTotalPageNum(1);
        }else{
            bookPage = this.bookServiceImpl.getBookPage(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        request.setAttribute("books",bookPage.getList());
        request.setAttribute("page", bookPage);

        return "admin/admin_book_manage/admin_book_list";
    }

    /* 搜索图书*/
    @RequestMapping(value = "searchBook",method = RequestMethod.POST)
    public String searchBook(@RequestParam("bookId") String bookId,
                             @RequestParam("bookName") String bookName,
                             @RequestParam("author") String author,
                             @RequestParam("ISBN") String ISBN,
                              HttpServletRequest request){
        List<Book> books;
        Map paramsMap = new HashMap();
        if(!bookId.equals("")){     //根据ID查找
            paramsMap.put("bookId",Integer.parseInt(bookId));
        }else if(!ISBN.equals("")){
            paramsMap.put("ISBN",ISBN);
        }else if(!bookName.equals("")){
            paramsMap.put("name",bookName);
        } else { //根据书名和作者查找
            paramsMap.put("author",author);
        }

        books = this.bookServiceImpl.getBooks(paramsMap);
        request.setAttribute("books",books);

        return "admin/admin_book_manage/admin_bookSearch_list";
    }

    /* 根据条件跳转到图书列表 如已借出、未借出等 */
    @RequestMapping("bookListPageByState")
    public String bookListPageByState(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                      @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                      @RequestParam(name="state") int state,
                                      HttpServletRequest request){
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("state",state);
        Page<Book> bookPage;

        if(pageSize.equals("all")){
            List <Book> books = this.bookServiceImpl.getBooks(paramsMap);
            bookPage = new Page<>();
            bookPage.setPageSize(books.size());
            bookPage.setTotalCount(books.size());
            bookPage.setList(books);
            bookPage.setCurrentPageNum(1);
            bookPage.setTotalPageNum(1);
        }else{
            bookPage = this.bookServiceImpl.getBookPage(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        request.setAttribute("books",bookPage.getList());
        request.setAttribute("page", bookPage);
        request.setAttribute("state",state);

        return "admin/admin_book_manage/admin_book_list";
    }

    /* 删除图书操作*/
    @RequestMapping(value = "deleteBook",method = RequestMethod.POST)
    public String deleteBook(@RequestParam("bookId") String bookId,
                              HttpServletRequest request){
        String contextPath = request.getSession().getServletContext().getRealPath("/");
        Book book = this.bookServiceImpl.getBook(Integer.parseInt(bookId));
		/*判断图书是否存在*/
        if(book == null){
            request.setAttribute("error","图书不存在");
            return "redirect:/admin/bookListPage";
        }
        this.bookServiceImpl.deleteBook(Integer.parseInt(bookId),contextPath);

        return "admin/admin_success";
    }

    /* 删除图书组操作*/
    @RequestMapping(value = "deleteBookGroup",method = RequestMethod.POST)
    public String deleteBookGroup(@RequestParam("bookList") String bookList,
                                   HttpServletRequest request){
        String[] books = bookList.split(",");
        String contextPath = request.getSession().getServletContext().getRealPath("/");
        int[] b = new int[books.length];

        for(int i = 0;i < books.length;++i){
            b[i] = Integer.parseInt(books[i]);
        }

        this.bookServiceImpl.deleteBookGroup(b,contextPath);

        return "admin/admin_success";
    }

    /* 编辑图书信息页面*/
    @RequestMapping(value = "editBookPage",method = RequestMethod.GET)
    public String editBookPage(@RequestParam("bookId") String bookId,
                                HttpServletRequest request,RedirectAttributes attr){
        Book book = this.bookServiceImpl.getBook(Integer.parseInt(bookId));
        List<BookClass> bookClasses = this.bookClassServiceImpl.getAllBookClasses();

        request.setAttribute("book",book);
        request.setAttribute("bookClasses",bookClasses);
        request.setAttribute("success",attr.getFlashAttributes().get("success"));

        return "admin/admin_book_manage/admin_book_info";
    }

    /* 更新图书信息操作*/
    @RequestMapping(value = "updateBook",method = RequestMethod.POST)
    public String updateStaff(@RequestParam("bookId") String bookId,
                              @RequestParam("bookName") String bookName,
                              @RequestParam("author") String author,
                              @RequestParam("publish") String publish,
                              @RequestParam("bookPrice") String bookPrice,
                              @RequestParam("ISBN") String ISBN,
                              @RequestParam("bookClass") String bookClass,
                              @RequestParam("bookState") String bookState){
        Book book = this.bookServiceImpl.getBook(Integer.parseInt(bookId));

        book.setAuthor(author);
        book.setName(bookName);
        book.setBookClass(bookClassServiceImpl.getBookClass(Integer.parseInt(bookClass)));
        book.setPublish(publish);
        book.setISBN(ISBN);
        book.setPrice(Float.parseFloat(bookPrice));
        book.setState(Integer.parseInt(bookState));

        this.bookServiceImpl.editBook(book);

        return "admin/admin_success";
    }

    /* 编辑图书封面图页面*/
    @RequestMapping(value = "editBookImagePage",method = RequestMethod.GET)
    public String editBookImagePage(@RequestParam("bookId") String bookId,
                               HttpServletRequest request){
        Book book = this.bookServiceImpl.getBook(Integer.parseInt(bookId));
        request.setAttribute("book",book);

        return "admin/admin_book_manage/admin_bookImage_update";
    }

    /* 更新图书封面操作*/
    @RequestMapping(value = "updateBookImage",method = RequestMethod.POST)
    public String updateBookImage(@RequestParam("bookId") String bookId,
                               MultipartHttpServletRequest multipartRequest,HttpServletRequest request, RedirectAttributes attr){
        String contextPath = request.getSession().getServletContext().getRealPath("/");
        MultipartFile imgFile =  multipartRequest.getFile("book_img");
        Book book = this.bookServiceImpl.getBook(Integer.parseInt(bookId));
        this.bookServiceImpl.editBookImage(book,contextPath,imgFile);

        attr.addFlashAttribute("success","更新成功");
        attr.addAttribute("bookId",bookId);

        return"redirect:/admin/editBookPage";
    }

    /* 改变图书丢失状态操作*/
    @RequestMapping(value = "findBook",method = RequestMethod.POST)
    public String findBook(@RequestParam("bookId") String bookId,RedirectAttributes attr){
        Book book = this.bookServiceImpl.getBook(Integer.parseInt(bookId));
		/*判断图书是否存在*/
        if(book == null){
            attr.addFlashAttribute("error","图书不存在");
            return "redirect:/admin/bookListPage";
        }else if(book.getState() != 2){
            attr.addFlashAttribute("error","图书不在丢失状态.");
            return "redirect:/admin/bookListPage";
        }

        book.setState(BookState.ENABLE_BORROW.getState());
        this.bookServiceImpl.editBook(book);

        return "redirect:/admin/bookListPage";
    }
    /******************借阅管理：基本增删改查***************/
      /* 图书借阅页面*/
    @RequestMapping("borrowManagePage")
    public String borrowManagePage(){
        return "admin/admin_borrow_manage/admin_borrow_manage";
    }

    /* 跳转到全部借阅列表*/
    @RequestMapping("allBorrowListPage")
    public String allBorrowListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                    @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                    HttpServletRequest request,RedirectAttributes attr){
        Page<Borrow> borrowPage;
        Map<String,Object> paramsMap = new HashMap<>();

        if(pageSize.equals("all")){
            List<Borrow> borrows = this.borrowServiceImpl.getAllBorrows();
            borrowPage = new Page<>();
            borrowPage.setPageSize(borrows.size());
            borrowPage.setTotalCount(borrows.size());
            borrowPage.setList(borrows);
            borrowPage.setCurrentPageNum(1);
            borrowPage.setTotalPageNum(1);
        }else{
            borrowPage = this.borrowServiceImpl.getAllBorrows(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        if(attr.getFlashAttributes().get("success") != null){
            request.setAttribute("success",attr.getFlashAttributes().get("success"));
        }else if(attr.getFlashAttributes().get("error") != null){
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        }

        request.setAttribute("borrows",borrowPage.getList());
        request.setAttribute("page", borrowPage);
        request.setAttribute("type",0);

        return "admin/admin_borrow_manage/admin_borrow_list";
    }


    /* 根据条件跳转到借阅列表 如已借出、已丢失等*/
    @RequestMapping("borrowListPageByState")
    public String borrowListPageByState(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                        @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                         @RequestParam("type") int type,
                                        HttpServletRequest request){
        Page<Borrow>borrowPage;
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("state",type - 1);

        if(pageSize.equals("all")){
            List<Borrow> borrows = this.borrowServiceImpl.getBorrows(paramsMap);
            borrowPage = new Page<>();
            borrowPage.setList(borrows);
            borrowPage.setPageSize(borrows.size());
            borrowPage.setTotalCount(borrows.size());
            borrowPage.setCurrentPageNum(1);
            borrowPage.setTotalPageNum(1);
        }else{
            borrowPage = this.borrowServiceImpl.getBorrowPage(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        request.setAttribute("borrows",borrowPage.getList());
        request.setAttribute("page", borrowPage);
        request.setAttribute("type",type);

        return "admin/admin_borrow_manage/admin_borrow_list";
    }

    /* 确认借阅单号操作，如确认取书，确认还书， */
    @RequestMapping(value = "ensureBorrow",method = RequestMethod.POST)
    public String ensureBorrow( @RequestParam("borrowId") int borrowId,
                                 @RequestParam("type") String type,
                              HttpServletRequest request,RedirectAttributes attr){
        Borrow borrow = this.borrowServiceImpl.getBorrow(borrowId);
        Book book = borrow.getBook();

        if(type.equals("1")){
            attr.addAttribute("username",borrow.getStaff().getUsername());
            attr.addAttribute("type",0);
        }

        if(borrow.getState() == BorrowState.GETTING_BOOK.getState()){ //  确认取书
            borrow.setState(BorrowState.BORROWING_BOOK_BOOKS.getState());   //设置为正在借阅
        }else if(borrow.getState() == BorrowState.RETURNING_BOOK.getState()){   //确认还书
            borrow.setState(BorrowState.RETURNED_BOOK.getState());  //设置为已归还
            book.setState(BookState.ENABLE_BORROW.getState());

            this.bookServiceImpl.editBook(book);
        }else{
            attr.addFlashAttribute("error","失败,该记录已过期");
            if(type.equals("1")){
                return"redirect:/admin/searchBorrows";
            } else {
                return"redirect:/admin/allBorrowListPage";
            }
        }
        borrow.setAdmin((Administrator) request.getSession().getAttribute("admin"));

        this.borrowServiceImpl.updateBorrow(borrow);

        attr.addFlashAttribute("success","处理成功");
        if(type.equals("1")){
            return"redirect:/admin/searchBorrows";
        }else{
            return"redirect:/admin/allBorrowListPage";
        }
    }

    /* 催还操作 */
    @ResponseBody
    @RequestMapping(value = "urgeReturnBook",method = RequestMethod.POST)
    public ReturnJson urgeReturnBook( @RequestBody Map<String, String> params){
        int borrowId = Integer.parseInt(params.get("borrowId"));
        String subject = "内部图书管理系统_图书催还";
        Borrow borrow = this.borrowServiceImpl.getBorrow(borrowId);
        Staff staff = borrow.getStaff();
        Book book = borrow.getBook();
        StringBuffer stringBuffer = new StringBuffer();
        Map<String,Object> data = new HashMap();

        //判断当前借阅状态
        if(borrow.getState() != BorrowState.OUTDATE_BOOK.getState() && borrow.getState() != BorrowState.RETURNING_BOOK.getState()
                && borrow.getState() != BorrowState.BORROWING_BOOK_BOOKS.getState()){
            return new ReturnJson(false,"失败,当前借阅状态并不在借阅");
        }else{
            stringBuffer.append("亲爱的" + staff.getName());
            stringBuffer.append(",请及时归还图书");
            stringBuffer.append("《"+book.getName() + "》");
            new SendMessage().send("companylibrary@sina.com","administrator",staff.getEmail(),subject,stringBuffer.toString());      /* 发送邮件 */
            return new ReturnJson(true,null,data);
        }
    }

    /* 违约处理借阅操作，如超期,挂失,等， */
    @RequestMapping(value = "deal",method = RequestMethod.POST)
    public String deal(@RequestParam("borrowId") int borrowId,
                        @RequestParam("staffId") String staffId,
                        @RequestParam("money") String money,
                        @RequestParam("date") String date,
                        @RequestParam("type") String type,
                        HttpServletRequest request,RedirectAttributes attr){
        Borrow borrow = this.borrowServiceImpl.getBorrow(borrowId);
        Payment payment = new Payment();

        payment.setStaff(this.staffServiceImpl.getStaff(Integer.parseInt(staffId)));
        payment.setAdmin((Administrator) request.getSession().getAttribute("admin"));
        payment.setMoney(Float.parseFloat(money));
        payment.setDate(date);
        payment.setBook(borrow.getBook());

        if(type.equals("1")){
            attr.addAttribute("username",borrow.getStaff().getUsername());
            attr.addAttribute("type",0);
        }

        if(borrow.getState() == BorrowState.OUTDATE_BOOK.getState()){ //  超期
            payment.setReason(1);
        }else if(borrow.getState() == BorrowState.LOST_BOOK.getState()){   //挂失
            payment.setReason(2);
        }else{
            attr.addFlashAttribute("error","失败,该记录已过期");
            if(type.equals("1")){
                return"redirect:/admin/searchBorrows";
            } else {
                return"redirect:/admin/allBorrowListPage";
            }
        }
        borrow.setState(BorrowState.RETURNED_BOOK.getState());

        this.borrowServiceImpl.updateBorrow(borrow);
        this.paymentServiceImpl.addPayment(payment);

        attr.addFlashAttribute("success","处理成功");
        if(type.equals("1")){
            return"redirect:/admin/searchBorrows";
        }else{
            return"redirect:/admin/allBorrowListPage";
        }
    }

    /* 根据员工号来查找正在借阅的单号 */
    @RequestMapping("searchBorrows")
    public String searchBorrows( @RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                 @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                 @RequestParam("username") String username,
                                 @RequestParam("type") int type,
                                 RedirectAttributes attr, HttpServletRequest request){
        Page<Borrow>borrowPage;
        Staff staff = this.staffServiceImpl.getStaff(username);
        List<Borrow> borrows;

        if(type == 0) {
            if(pageSize.equals("all")){
                borrows = this.borrowServiceImpl.getCurrentBorrowsByStaff(staff);
                borrowPage = new Page<>();
                borrowPage.setList(borrows);
                borrowPage.setPageSize(borrows.size());
                borrowPage.setTotalCount(borrows.size());
                borrowPage.setCurrentPageNum(1);
                borrowPage.setTotalPageNum(1);
            }else{
                borrowPage = this.borrowServiceImpl.getCurrentBorrowsByStaff(pageNum,Integer.parseInt(pageSize),staff);
            }
        } else {
            if(pageSize.equals("all")){
                borrows = this.borrowServiceImpl.getHistoryBorrowsByStaff(staff);
                borrowPage = new Page<>();
                borrowPage.setList(borrows);
                borrowPage.setPageSize(borrows.size());
                borrowPage.setTotalCount(borrows.size());
                borrowPage.setCurrentPageNum(1);
                borrowPage.setTotalPageNum(1);
            }else{
                borrowPage = this.borrowServiceImpl.getHistoryBorrowsByStaff(pageNum,Integer.parseInt(pageSize),staff);
            }
        }

        request.setAttribute("page",borrowPage);
        request.setAttribute("borrows",borrowPage.getList());
        request.setAttribute("staff",staff);
        request.setAttribute("success",attr.getFlashAttributes().get("success"));
        request.setAttribute("username",username);
        request.setAttribute("type",type);

        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));

        return "admin/admin_borrow_manage/admin_staffBorrow_list";
    }

    /* 全部缴费记录 */
    @RequestMapping("allPaymentsListPage")
    public String allPaymentsListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                        @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                        HttpServletRequest request){
        Page<Payment>paymentPage;
        Map<String,Object> paramsMap = new HashMap<>();

        if(pageSize.equals("all")){
            List<Payment> payments = this.paymentServiceImpl.getAllPayments();
            paymentPage = new Page<>();
            paymentPage.setList(payments);
            paymentPage.setPageSize(payments.size());
            paymentPage.setTotalCount(payments.size());
            paymentPage.setCurrentPageNum(1);
            paymentPage.setTotalPageNum(1);
        }else{
            paymentPage = this.paymentServiceImpl.getPageByParams(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        request.setAttribute("payments",paymentPage.getList());
        request.setAttribute("page", paymentPage);

        return "admin/admin_payment_manage/admin_payment_list";
    }

    /*************缴费记录管理**************/
    /* 缴费记录搜索页面*/
    @RequestMapping("paymentManagePage")
    public String paymentManagePage(){
        return "admin/admin_payment_manage/admin_payment_manage";
    }


    /* 全部缴费记录 */
    @RequestMapping("paymentsListPageByReason")
    public String paymentsListPageByReason(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                      @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                      @RequestParam(name = "reason")  int reason,
                                      HttpServletRequest request){
        Page<Payment>paymentPage;
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("reason",reason);

        if(pageSize.equals("all")){
            List<Payment> payments = this.paymentServiceImpl.getPaymentsByParams(paramsMap);
            paymentPage = new Page<>();
            paymentPage.setList(payments);
            paymentPage.setPageSize(payments.size());
            paymentPage.setTotalCount(payments.size());
            paymentPage.setCurrentPageNum(1);
            paymentPage.setTotalPageNum(1);
        }else{
            paymentPage = this.paymentServiceImpl.getPageByParams(pageNum,Integer.parseInt(pageSize),paramsMap);
        }

        request.setAttribute("payments",paymentPage.getList());
        request.setAttribute("page", paymentPage);
        request.setAttribute("type",reason);

        return "admin/admin_payment_manage/admin_payment_list";
    }

    /* 根据员工号来查找正在借阅的单号 */
    @RequestMapping("searchPayments")
    public String searchPayments( @RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                 @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                 @RequestParam("username") String username,
                                 @RequestParam("type") int type,
                                 RedirectAttributes attr, HttpServletRequest request){
        Page<Payment>paymentPage;
        Staff staff = this.staffServiceImpl.getStaff(username);
        List<Payment>payments;
        Map paramsMap = new HashMap();

        paramsMap.put("staff",staff);
        if(type == 0) {
            if(pageSize.equals("all")){
                payments = this.paymentServiceImpl.getPaymentsByParams(paramsMap);
                paymentPage = new Page<>();
                paymentPage.setList(payments);
                paymentPage.setPageSize(payments.size());
                paymentPage.setTotalCount(payments.size());
                paymentPage.setCurrentPageNum(1);
                paymentPage.setTotalPageNum(1);
            }else{
                paymentPage = this.paymentServiceImpl.getPageByParams(pageNum,Integer.parseInt(pageSize),paramsMap);
            }
        } else {
            paramsMap.put("reason",type);
            if(pageSize.equals("all")){
                payments = this.paymentServiceImpl.getPaymentsByParams(paramsMap);
                paymentPage = new Page<>();
                paymentPage.setList(payments);
                paymentPage.setPageSize(payments.size());
                paymentPage.setTotalCount(payments.size());
                paymentPage.setCurrentPageNum(1);
                paymentPage.setTotalPageNum(1);
            }else{
                paymentPage = this.paymentServiceImpl.getPageByParams(pageNum,Integer.parseInt(pageSize),paramsMap);
            }
        }

        request.setAttribute("page",paymentPage);
        request.setAttribute("payments",paymentPage.getList());
        request.setAttribute("staff",staff);
        request.setAttribute("success",attr.getFlashAttributes().get("success"));
        request.setAttribute("username",username);
        request.setAttribute("type",type);

        if(attr.getFlashAttributes().get("error") != null)
            request.setAttribute("error",attr.getFlashAttributes().get("error"));

        return "admin/admin_payment_manage/admin_staffPayment_list";
    }

    /****************评论管理***************/
    /* 查看评论页面 */
    @RequestMapping("evaluateListPage")
    public String evaluateListPage(@RequestParam(name="pageNum", defaultValue="1") int pageNum,
                                    @RequestParam(name="pageSize", defaultValue="10") String pageSize,
                                    HttpServletRequest request,RedirectAttributes attr){
        Page<Evaluate>evaluatePage;
        Map<String,Object> paramsMap = new HashMap<>();

        if(pageSize.equals("all")){
            List<Evaluate> evaluates = this.evaluateServiceImpl.getAllEvaluateOrderByPraiseDesc();
            evaluatePage = new Page<>();
            evaluatePage.setList(evaluates);
            evaluatePage.setPageSize(evaluates.size());
            evaluatePage.setTotalCount(evaluates.size());
            evaluatePage.setCurrentPageNum(1);
            evaluatePage.setTotalPageNum(1);
        }else{
            evaluatePage = this.evaluateServiceImpl.getAllPageOrderByPraiseForbidden(pageNum,Integer.parseInt(pageSize));
        }
        if(attr.getFlashAttributes().get("success") != null){
            request.setAttribute("success",attr.getFlashAttributes().get("success"));
        }else if(attr.getFlashAttributes().get("error") != null){
            request.setAttribute("error",attr.getFlashAttributes().get("error"));
        }

        request.setAttribute("page",evaluatePage);
        request.setAttribute("evaluates",evaluatePage.getList());

        return "admin/admin_evaluate_manage/admin_evaluate_list";
    }

    /* 查看评论内容操作*/
    @ResponseBody
    @RequestMapping(value = "checkEvaluateInfo",method = RequestMethod.POST)
    public ReturnJson checkEvaluateInfo(@RequestBody Map<String, String> params){
        String evaluateId = params.get("evaluateId");
        Map<String,Object> data = new HashMap();

        	/*判断评论是否存在*/
        if(this.evaluateServiceImpl.getEvaluateById(Integer.parseInt(evaluateId)) == null){
            return new ReturnJson(false,"失败了,评论不存在");
        }
        Evaluate evaluate = this.evaluateServiceImpl.getEvaluateById(Integer.parseInt(evaluateId));

        data.put("evaluateContent",evaluate.getDescription());
        return new ReturnJson(true,null,data);
    }

    /* 删除评论操作*/
    @RequestMapping(value = "deleteEvaluate",method = RequestMethod.POST)
    public String deleteEvaluate(@RequestParam("evaluateId") int evaluateId,
                              HttpServletRequest request,RedirectAttributes attr){
		/*判断评论是否存在*/
        if(this.evaluateServiceImpl.getEvaluateById(evaluateId) == null){
            attr.addFlashAttribute("error","评论不存在");
            return "redirect:/admin/evaluateListPage";
        }
        this.evaluateServiceImpl.deleteEvaluate(evaluateId);
        attr.addFlashAttribute("success","删除成功");

        return "redirect:/admin/evaluateListPage";
    }

    /* 删除员工组操作*/
    @RequestMapping(value = "deleteEvaluateGroup",method = RequestMethod.POST)
    public String deleteEvaluateGroup(@RequestParam("evaluateList") String evaluateList,
                                   HttpServletRequest request,RedirectAttributes attr){
        String[] evaluates = evaluateList.split(",");
        int[] e = new int[evaluates.length];

        for(int i = 0;i < evaluates.length;++i){
            e[i] = Integer.parseInt(evaluates[i]);
        }this.evaluateServiceImpl.deleteEvaluateGroup(e);

        attr.addFlashAttribute("success","删除成功");

        return "redirect:/admin/evaluateListPage";
    }

    /* 数据统计
     * @desc	返回本月和上个月的数据统计
     * @author	miaohuaiyu
     * @return	admin/admin_count
     */
    @RequestMapping(value = "countStatistic")
    public String countStatistic(HttpServletRequest request){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        Map paramsMap = new HashMap();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月

        //获得总统计记录 无用户
        paramsMap.put("staff",null);
        List<Statistic> statistics = this.statisticServiceImpl.getStatisticsByParams(paramsMap);
        for (int i = statistics.size() - 1;i > 5;--i){      //只保留五个
            statistics.remove(i);
        }

        paramsMap.put("date",formatter.format(date));
        Count presentMonthCount = this.countServiceImpl.getCountByParams(paramsMap);   //本月

        paramsMap.put("date",formatter.format(calendar.getTime()));     //上个月
        Count lastMonthCount = this.countServiceImpl.getCountByParams(paramsMap);

        paramsMap.clear();
        int booksCount = this.bookServiceImpl.getBooksCountByParams(paramsMap) == null ? 0:this.bookServiceImpl.getBooksCountByParams(paramsMap).intValue();
        int borrowCount = this.borrowServiceImpl.getBorrowsCountByParams(paramsMap) == null ? 0 : this.borrowServiceImpl.getBorrowsCountByParams(paramsMap).intValue();
        int staffCount = this.staffServiceImpl.getStaffsCountByParams(paramsMap) == null ? 0:this.staffServiceImpl.getStaffsCountByParams(paramsMap).intValue();
        int evaluateCount = this.evaluateServiceImpl.getEvaluatesCountByParams(paramsMap) == null ?0: this.evaluateServiceImpl.getEvaluatesCountByParams(paramsMap).intValue();
        int searchCount = this.searchServiceImpl.getStaffSearchsCountByParams(paramsMap) == null ? 0: this.searchServiceImpl.getStaffSearchsCountByParams(paramsMap).intValue();
        int paymentCount = this.paymentServiceImpl.getPaymentCostByParams(paramsMap) == null? 0 : this.paymentServiceImpl.getPaymentCostByParams(paramsMap).intValue();

        if(presentMonthCount != null){
            presentMonthCount.setBookCount(booksCount);
            presentMonthCount.setBorrowCount(borrowCount);
            presentMonthCount.setStaffCount(staffCount);
            presentMonthCount.setEvaluateCount(evaluateCount);
            presentMonthCount.setSearchCount(searchCount);
            presentMonthCount.setPaymentCount(paymentCount);
            this.countServiceImpl.updateCount(presentMonthCount);
        } else{
            presentMonthCount = new Count();

            presentMonthCount.setBookCount(booksCount);
            presentMonthCount.setBorrowCount(borrowCount);
            presentMonthCount.setStaffCount(staffCount);
            presentMonthCount.setEvaluateCount(evaluateCount);
            presentMonthCount.setSearchCount(searchCount);
            presentMonthCount.setPaymentCount(paymentCount);
            presentMonthCount.setDate(formatter.format(date));

            this.countServiceImpl.addCount(presentMonthCount);
        }
        request.setAttribute("presentMonthCount",presentMonthCount);

        if(lastMonthCount != null){
            request.setAttribute("lastMonthCount",lastMonthCount);
        }

        if(statistics != null){
            request.setAttribute("statistics",statistics);
        }

        return "admin/admin_count";
    }

}
